package com.atguigu.lease.common.handle;

import com.atguigu.lease.model.enums.BaseTypeEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class StringToBaseTypeEnumConverterFactory implements ConverterFactory<String, BaseTypeEnum> {
    @Override
    public <T extends BaseTypeEnum> Converter<String, T> getConverter(Class<T> targetType) {

        return new Converter<String, T>() {

            @Override
            public T convert(String source) {
                for (T enumConstant : targetType.getEnumConstants()) {
                    if(enumConstant.getCode().equals(Integer.parseInt(source))) {
                        return enumConstant;
                    }
                }
                throw new RuntimeException("转换器工厂-创建转换器-无法匹配对应的类型");
            }
        };
    }
}
